#include "music_dialog.h"
#include "ui_music_dialog.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QTimer>
#include <QStandardPaths>
#include <QJsonDocument>
#include <QJsonObject>
#include <QIcon>
#include <QTime>
#include <QJsonDocument>
#include <QJsonObject>
#include <QNetworkRequest>

music_dialog::music_dialog(QWidget *parent):
    QDialog(parent),
    ui(new Ui::music_dialog),
    m_music(new My_music (this)),
    m_jsonparser(new Music_Json (this)),
    m_lyricParser(new music_lyricparser ()),
    m_lyricTimer(new QTimer (this)),
    m_networkManager(new QNetworkAccessManager(this))
{
    ui->setupUi(this);
    
    
    
    //连接信号与槽
    connect(ui->Slider_volume, &QSlider::valueChanged, this, &music_dialog::onVolumeChanged);
    connect(ui->Slider_position, &QSlider::sliderMoved, this, &music_dialog::onSliderMoved);
       
    connect(m_music, &My_music::positionChanged, this, &music_dialog::onPositionChanged);
    connect(m_music, &My_music::mediaStatusChanged, this, &music_dialog::onMediaStatusChanged);
    connect(m_music, &My_music::currentIndexChanged, this, &music_dialog::onCurrentIndexChanged);
    connect(m_music->music, &QMediaPlayer::durationChanged, this, &music_dialog::onDurationChanged);
       
       // 歌词更新定时器
    connect(m_lyricTimer, &QTimer::timeout, this, &music_dialog::updateLyrics);
    m_lyricTimer->start(100);
       
       // 加载音乐列表
    loadSongs();
    ui->Slider_volume->setValue(50);
    
}

music_dialog::~music_dialog()
{
        delete ui;
        delete m_lyricParser;
        delete m_music;
        delete m_jsonparser;
        delete m_lyricTimer;
        delete m_networkManager;
}




void music_dialog::on_Button_play_pause_clicked()
{
    if(m_music->state() == QMediaPlayer::PlayingState)
    {
        m_music->pause();
        ui->Button_play_pause->setIcon(QIcon(":/new/prefix1/播放"));
    }
    else
    {
        m_music->play();
        ui->Button_play_pause->setIcon(QIcon(":/new/prefix1/暂停"));
    }

}

void music_dialog::on_Button_pervious_clicked()
{
    int current = m_music->currentIndex();
    if(current >0)
    {
        m_music->setCurrentIndex(current -1);
    }
}

void music_dialog::on_Button_next_clicked()
{
    int current = m_music->currentIndex();
        if(current < songs.size() - 1) {
            m_music->setCurrentIndex(current + 1);
        } else {
            m_music->setCurrentIndex(0); // 循环到开头
        }
}

void music_dialog::onVolumeChanged(int volume)
{
    m_music->setVolume(volume);
    ui->label_Volume->setText(QString("%1%").arg(volume));
}

void music_dialog::onPositionChanged(qint64 position)
{
    ui->Slider_position->setValue(position);
        
        // 转换为分钟和秒
        int seconds = position / 1000;  // 总秒数
        int minutes = seconds / 60;     // 分钟部分
        seconds = seconds % 60;         // 剩余秒数
        
        // 格式化为"分:秒"（如0:25）
        ui->currentTime_Label->setText(
            QString("%1:%2")
                .arg(minutes)
                .arg(seconds, 2, 10, QLatin1Char('0')));
}

void music_dialog::onDurationChanged(qint64 duration)
{
    ui->Slider_position->setRange(0, duration);
        
        // 转换为分钟和秒
        int seconds = duration / 1000;  // 总秒数
        int minutes = seconds / 60;     // 分钟部分
        seconds = seconds % 60;         // 剩余秒数
        
        // 格式化为"分:秒"（如3:45）
        ui->totalTime_Label->setText(
            QString("%1:%2")
                .arg(minutes)
                .arg(seconds, 2, 10, QLatin1Char('0')));
}

void music_dialog::onSliderMoved(int position)
{
    m_music->music->setPosition(position);
}

void music_dialog::onMediaStatusChanged(QMediaPlayer::MediaStatus status)
{
    if (status == QMediaPlayer::LoadedMedia) 
    {
            onDurationChanged(m_music->music->duration());
    }
}

void music_dialog::onCurrentIndexChanged(int position)
{
    if (position >= 0 && position < songs.size())
    {
            updateSongInfo(position);
            loadLyrics(position);

    }
    
}

void music_dialog::updateLyrics()
{
    if (m_music->state() != QMediaPlayer::PlayingState || m_currentLyrics.isEmpty()) {
            return;
        }
        
        qint64 position = m_music->music->position();
        QString currentLyric = "暂无歌词";
        
        // 查找当前时间对应的歌词
        for (int i = 0; i < m_currentLyrics.size(); ++i) {
            if ((i < m_currentLyrics.size() - 1 && 
                 position >= m_currentLyrics[i].timeMs && 
                 position < m_currentLyrics[i+1].timeMs) ||
                (i == m_currentLyrics.size() - 1 && 
                 position >= m_currentLyrics[i].timeMs)) {
                currentLyric = m_currentLyrics[i].content;
                break;
            }
        }
        
        ui->lyric_label->setText(currentLyric);
}



void music_dialog::loadSongs()
{
    m_music->clearPlaylist();
    
    m_music->addMedia(QUrl("http://music.163.com/song/media/outer/url?id=1981224611.mp3"));
    m_music->addMedia(QUrl("http://music.163.com/song/media/outer/url?id=2651457023.mp3"));
    m_music->addMedia(QUrl("http://music.163.com/song/media/outer/url?id=1927326447.mp3"));
    m_music->addMedia(QUrl("http://music.163.com/song/media/outer/url?id=2016804746.mp3"));
    m_music->addMedia(QUrl("http://music.163.com/song/media/outer/url?id=2051697474.mp3"));
    m_music->addMedia(QUrl("http://music.163.com/song/media/outer/url?id=1346907833.mp3"));
    m_music->addMedia(QUrl("http://music.163.com/song/media/outer/url?id=1823238771.mp3"));
    m_music->addMedia(QUrl("http://music.163.com/song/media/outer/url?id=1812390276.mp3"));
    
    
    
    // 设置对应的歌曲信息
    songs = {
        {1981224611, "花脸", 0, "GO哥_Official"},
        {2651457023, "诶嘿", 0, "GO哥_Official"},
        {1927326447, "Under Bright Lights", 0, "Ekko & Sidetrack"},
        {2016804746, "All Night", 0, "KILL SCRIPT"},
        {2051697474, "reason", 0, "Rad Cat"},
        {1346907833, "EZ4ENCE", 0, "The Verkkars"},
        {1823238771, "El Vals Del Taco de Rana", 0, "Dren Mcdonald"},
        {1812390276, "dashstar*", 0, "Knock2"}
        
          
      };
    
    if (!songs.isEmpty()) {
           updateSongInfo(0);
       }
}

void music_dialog::updateSongInfo(int index)
{
    if (index >= 0 && index < songs.size()) {
           const SongInfo &song = songs[index];
           ui->music_info_name->setText(QString("%1 - %2").arg(song.song_name, song.singer_name));
       }
}
void music_dialog::fetchLyricsFromNetEase(qint64 songId)
{
    // 构建网易云音乐歌词API URL
       QString lyricsUrl = QString("http://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1").arg(songId);
       
       // 发送网络请求获取歌词
       QNetworkRequest request;
       request.setUrl(QUrl(lyricsUrl));
       request.setRawHeader("Referer", "http://music.163.com");
       
       QNetworkReply *reply = m_networkManager->get(request);
       
       connect(reply, &QNetworkReply::finished, this, [this, reply]() {
           if (reply->error() == QNetworkReply::NoError) {
               QByteArray data = reply->readAll();
               QJsonParseError error;
               QJsonDocument doc = QJsonDocument::fromJson(data, &error);
               
               if (error.error == QJsonParseError::NoError) {
                   QJsonObject obj = doc.object();
                   if (obj.contains("lrc")) {
                       QString lyricText = obj["lrc"].toObject().value("lyric").toString();
                       
                       // 使用歌词解析器解析歌词
                       m_lyricParser->setJson(doc.toJson());
                       m_currentLyrics = m_lyricParser->getLrcList();
                       
                       // 如果没有获取到歌词，显示默认提示
                       if (m_currentLyrics.isEmpty()) {
                           ui->lyric_label->setText("暂无歌词");
                       }
                   }
               } else {
                   ui->lyric_label->setText("歌词解析失败");
                   qWarning() << "JSON parse error:" << error.errorString();
               }
           } else {
               ui->lyric_label->setText("歌词加载失败");
               qWarning() << "Network error:" << reply->errorString();
           }
           
           reply->deleteLater();
       });
}

void music_dialog::loadLyrics(int index)
{
    if (index >= 0 && index < songs.size()) {
            qint64 songId = songs[index].song_id;
            fetchLyricsFromNetEase(songId);
        }
}






